using System;
using System.Collections.Generic;
using System.Text;
using Musicman.Entities;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Musicman.Common;
using System.Data.Common;

namespace Musicman.DAL
{
    public static class SearchFileStatsDAO
    {

        public static SearchFileStat GetFileStat(long fileID)
        {
            string sql = String.Format("SELECT SEARCHFILEID, TOTALDOWNLOADS, TOTALVOTED, RATING FROM FILESSTATS WHERE SEARCHFILEID = {0}", fileID);
            SearchFileStat res = new SearchFileStat();
            IDataReader reader = null;
            try
            {
                SqlDatabase db = new SqlDatabase(AppSettingsHelper.GetWebConfigValue(Constants.MusicmanConnectionString));
                reader = db.ExecuteReader(CommandType.Text, sql);
                if (reader != null)
                {
                    if (reader.Read())
                    {
                        res.SearchFileID = reader.GetInt64(0);
                        res.TotalDownloads = reader.IsDBNull(1) ? null : (int?)reader.GetInt32(1);
                        res.TotalVoted = reader.IsDBNull(2) ? null : (int?)reader.GetInt32(2);
                        res.Rating = reader.IsDBNull(3) ? null : (decimal?)reader.GetDecimal(3);
                    }
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                if (reader != null && !reader.IsClosed)
                {
                    reader.Close();
                }
                res = null;
                throw ex;
            }
            return res;
        }
        
        private static string updateProcName = "musicman.dbo.UpdateFileStats";
        private static DbCommand updateCommand = null;
        private static DbCommand GetUpdateCommand(SqlDatabase db)
        {
            if (updateCommand == null)
            {
                updateCommand = db.GetStoredProcCommand(updateProcName);
                db.AddInParameter(updateCommand, "@SearchFileID", DbType.Int64);
                db.AddInParameter(updateCommand, "@mark", DbType.Int32);
            }
            return updateCommand;
        }
        

        public static bool UpdateFileStats(long searchFileID, int mark)
        {
            bool res = false;
            SqlDatabase db = new SqlDatabase(AppSettingsHelper.GetWebConfigValue(Constants.MusicmanConnectionString));
            DbCommand cmd = GetUpdateCommand(db);
            db.SetParameterValue(cmd, "@SearchFileID", searchFileID);
            db.SetParameterValue(cmd, "@mark", mark);
            res = Convert.ToBoolean(db.ExecuteNonQuery(cmd));
            return res;
        }
    }
}
